package ntu.p2p.dht;

import java.io.IOException;

import rice.p2p.commonapi.Endpoint;
import rice.p2p.commonapi.rawserialization.InputBuffer;
import ntu.p2p.dht.messaging.DHTDifferenceDeserializer;
import ntu.p2p.dht.messaging.DHTObjectDifference;
import ntu.p2p.dht.messaging.DHTUpdateObjectMessage;
import ntu.p2p.dht.messaging.InsertObjectMessage;
import ntu.p2p.past.messaging.ObjectDifference;
import ntu.p2p.past.messaging.ObjectDifferenceContentDeserializer;
import ntu.p2p.past.messaging.UpdateObjectMessage;

public class PastObjectDifferenceDeserializer implements
		ObjectDifferenceContentDeserializer {

	private DHTContentDeserializer objectDeserializer;
	private DHTDifferenceDeserializer differenceDeserializer;
	
	public PastObjectDifferenceDeserializer(
			DHTContentDeserializer objectDeserializer, 
			DHTDifferenceDeserializer differenceDeserializer) {
		this.objectDeserializer = objectDeserializer;
		this.differenceDeserializer = differenceDeserializer;
	}
	
	@Override
	public ObjectDifference deserialize(final InputBuffer buf, Endpoint endpoint) {
		try {
			short type = buf.readShort();
			switch (type) {
			case InsertObjectMessage.TYPE:
				return InsertObjectMessage.build(buf, objectDeserializer, endpoint);
			case DHTUpdateObjectMessage.TYPE:
				return DHTUpdateObjectMessage.build(buf, differenceDeserializer, endpoint);
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return null;
	}

}
